package com.tansun.easycare.rule.ruletest.web;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import com.tansun.easycare.core.config.Global;
import com.tansun.easycare.core.utils.ResponseTable;
import com.tansun.easycare.rule.common.ResMessage;
import com.tansun.easycare.rule.common.RuleBaseController;
import com.tansun.easycare.rule.common.model.ResponseVO;
import com.tansun.easycare.rule.ruletest.entity.RuleTest;
import com.tansun.easycare.rule.ruletest.model.RuleTestInfo;
import com.tansun.easycare.rule.ruletest.service.RuleBatchTestService;
import com.tansun.easycare.rule.ruletest.service.RuleTestService;
import com.tansun.rule.utils.LoggerManager;

@RestController
@RequestMapping(value = "/ruleProj/batchTest")
public class BatchTestController extends RuleBaseController {

    @Autowired
    private RuleTestService ruleTestService;

    @Resource(name="RuleBigDataTestService")
    private RuleBatchTestService ruleBatchTestService;


    @RequestMapping("index")
    public ResponseTable<RuleTest>  doBatch(@RequestBody RuleTest ruleTest) throws Exception {
        ruleTest.setTestType("1");//单笔测试
        PageInfo<RuleTest> page = this.ruleTestService.findPage(ruleTest.getPage(), ruleTest);
        ResponseTable<RuleTest>  res  = new ResponseTable<>(page);
        return res;
    }

    @RequestMapping("add")
    public ResponseVO
    doAdd(@RequestBody RuleTest ruleTest) throws Exception {
        ResponseVO res = new ResponseVO();
        try {
            this.ruleBatchTestService.createBatchTest(ruleTest);
        } catch (Exception e) {
           res.setStatus(ResponseVO.ERROR);
           res.setDescription(e.getMessage());
        }
        return res;
    }

    @RequestMapping(value ="/dowmTemp{uploadType:.*}",method=RequestMethod.POST)
    public void doDowmTemp(@PathVariable String uploadType,@RequestBody RuleTestInfo  testInfo, HttpServletResponse response) throws Exception {
        if (StringUtils.isEmpty(testInfo.getId())) return;

        RuleTest ruleTest = this.ruleTestService.get(testInfo.getId());

        String[] downFile = this.ruleBatchTestService.createExcelTemp(testInfo.getProjectCode(), ruleTest);

        this.downTempFile(new File(downFile[0]), response, downFile[1]);
    }

    private void downTempFile(File file, HttpServletResponse response, String downName) throws IOException {
        OutputStream os = response.getOutputStream();
        try {
            response.setHeader("Content-Disposition", "attachment; filename=" + downName + ".xlsx");
            response.setContentType("application/octet-stream; charset=utf-8");
            os.write(FileUtils.readFileToByteArray(file));
            os.flush();
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }

    @RequestMapping("upload")
    public ResponseVO upload(@RequestParam("file") MultipartFile file,  @RequestParam("id") String id,@RequestParam("projectCode") String  projectCode) throws Exception {
        // MultipartFile对象转换
    	ResponseVO  res = new ResponseVO();
        ResMessage msg = null;
        String suffix = null;
        if (file.getOriginalFilename().endsWith(".xlsx")) {
            suffix = ".xlsx";

        }
        if (file.getOriginalFilename().endsWith(".xls")) {
            suffix = ".xls";

        }
        if (suffix == null) {
        	res.setStatus(ResponseVO.ERROR);
            return res;
        }
        msg = ruleBatchTestService.add(projectCode, id, file.getInputStream(), suffix);
        res.setDescription(JSONArray.toJSONString(msg));
        return res;
    }

    @RequestMapping("test")
    public ResponseVO test(@RequestBody RuleTestInfo  testInfo) throws Exception {
    	ResponseVO responseVO = new ResponseVO();
        //开始时间
        SimpleDateFormat spf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String t1 = spf.format(new Date());
        String  id = testInfo.getId();
        String  projectCode  = testInfo.getProjectCode();
        try {
             ruleBatchTestService.testExcel(projectCode, id);
        } catch (Exception e) {
            LoggerManager.error("", e, this.getClass());
            if (e.getCause() != null && e.getCause().getCause() != null && e.getCause().getCause() instanceof IndexOutOfBoundsException) {
                responseVO.setDescription("数组长度不够，请添加数据");
            } else {
            	Throwable root = ExceptionUtils.getRootCause(e);
    			if( root==null ) {
    				root = e;
    			}
                responseVO.setDescription("测试失败：" + root.getMessage());
                String desDetail = com.tansun.easycare.core.utils.StringUtils.toHtml(ExceptionUtils.getFullStackTrace(e));
                responseVO.setDesDetail(desDetail);
            }
            responseVO.setStatus(ResponseVO.ERROR);
            return responseVO;
        }
        String t2 = spf.format(new Date());
        System.out.println("#########################################测试开始时间:" + t1 + "  结束时间:" + t2 + "#########################################");
        responseVO.setDescription("成功计算测试，请下载进行查看结果！");
        responseVO.setStatus(ResponseVO.OK);
        return responseVO;
    }

    @RequestMapping( value="/download{uploadType:.*}",method=RequestMethod.POST)
    public void handle(@PathVariable String uploadType, HttpServletResponse res,@RequestBody RuleTestInfo  testInfo) throws Exception {

    	String  id  = testInfo.getId();
    	String  projectCode  = testInfo.getProjectCode();
        RuleTest ruleTest = this.ruleTestService.get(id);
        String path = Global.getConfig("file.uploadRoot") + File.separator + projectCode + RuleTest.UPDATE_BASE_PATH;
        String  tmpPath =path;
        if (ruleTest.getStatus().equals("11")) {
        	tmpPath = Global.getConfig("file.uploadRoot") + File.separator + projectCode + ruleTest.getResultPath();
        }
        path = tmpPath + File.separator + ruleTest.getId() + ".xls";
        String  filePath = path;
        File file = new File(path);
        if (!file.exists()) {
        	filePath = tmpPath + File.separator + ruleTest.getId() + ".xlsx";
            file = new File(filePath);
        }
        if (file.exists()) {
            OutputStream os = res.getOutputStream();
            res.setContentType("application/octet-stream; charset=utf-8");
            String filename = "testRusult.xlsx";
            res.setHeader("Content-Disposition", "attachment; filename=" + filename);
            try {
                os.write(FileUtils.readFileToByteArray(new File(filePath)));
                os.flush();
            } catch (Exception e) {
                LoggerManager.error("", e, this.getClass());
            } finally {
                if (os != null) {
                    os.close();
                }
            }
        }
    }


    @RequestMapping("del")
    public ResponseVO doDel(@RequestBody RuleTestInfo  testInfo) throws Exception {
    	ResponseVO res = new ResponseVO();//8.14该提示信息，原为空
        try {
            ruleBatchTestService.delBatchTest(testInfo.getId(),testInfo.getProjectCode());
        } catch (Exception e) {
            res.setStatus(ResponseVO.ERROR);
            res.setDescription("数据异常，删除失败！");  //8.14新增
        }
        return res;
    }


}
